const app = getApp()

import {
  showMsg
} from '../../utils/config.js'
import Dialog from '@vant/weapp/dialog/dialog';

let alarmHandle = require('../behaviors/alarm/handle.js')
let behaviorsOrgSelection = require('../behaviors/org/orgSelection.js')
let dictMixin = require('../behaviors/dict/dictMixin.js')

import {
  reqAlarmList,
  reqUntreatedAlarm,
  reqProductList,
  reqProductModel,
  reqOrgList,
  reqStatistics,
  reqhiddenDangerpage,
  reqworkOrderpage,
  reqworkOrderupdate,
  reqWorkOrder,
  reqHiddenDanger,
} from '../../request/api.js'
Page({
  behaviors: [alarmHandle, behaviorsOrgSelection ,dictMixin],
  data: {
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离
    navHeight: app.globalData.navHeight + 'px', //头部距离
    tenantId: '',

    tabList: [{
        id: 0,
        name: '告警',
        count: '',
        src: '/statics/images/alarm.png',
      }, {
        id: 1,
        name: '隐患',
        count: '',
        src: '/statics/images/message/device_msg.png',
      },
      {
        id: 2,
        name: '工单',
        count: '',
        src: '/statics/images/message/home_msg.png',
      },
    ],
    currentTab: 0, //当前tab

    productList: [], //产品列表
    classMarkList: [], //产品型号
    classMark: "",
    dataList: [],

    // 告警开始
    alarmList: [],
    alarmPage: 1,
    alarmSearchValue: '',
    alarmIsNextPage: true,
    alarmTriggered: false,
    // 筛选弹窗开始
    showSearch: false, //筛选弹窗
    statusList: [{
      id: '',
      name: '全部',
      active: true,
    }, {
      id: 1,
      name: '未处理',
      active: false,
    }, {
      id: 2,
      name: '处理中',
      active: false,
    }, {
      id: '3',
      name: '已处理',
      active: false,
    }, ],
    showAlarmTime: false, //时间弹窗
    alarmStartTime: '',
    alarmEndTime: '',
    timePickerConfig: { //时间弹窗组件
      isTabbar: true, //是否为tabbar页面
      endDate: true, // 是否需要结束时间，为true时显示开始时间和结束时间两个picker
      column: "minute", //可选的最小时间范围day、hour、minute、secend
      dateLimit: true,
      initStartTime: '', //默认开始时间
      initEndTime: '', //默认结束时间
      limitStartTime: "2000-01-01 00:00:00", //最小可选时间--必填
      limitEndTime: "2100-12-01 23:59:59" //最大可选时间--必填
    },
    alarmStatus: '', //已处理/处理中/未处理
    alarmType: '', //告警类型
    hasSearch: false, //是否有筛选
    total: "",
    // 筛选弹窗结束
    // 告警结束

    srcClassMsg: '/statics/images/message/class_msg.png',
    srcHomeMsg: '/statics/images/message/home_msg.png',
    srcDeviceMsg: '/statics/images/message/device_msg.png',
    alarmOffline: '/statics/images/device/alarm_offline.png', //离线告警

    // 隐患
    hiddenPage: 1,
    hiddenList: [],
    hiddenIsNextPage: true,
    hiddenTriggered: false,
    hiddenSource: "",
    hiddenType: "",
    hiddenStatus: "",
    hiddenStartTime: "",
    hiddenEndTime: "",
    hiddenSearchValue: '',
    showHiddenSearch: false, //筛选弹窗
    hasSearchHidden: false, //是否有筛选
    hiddenstatusList: [{
      id: '',
      name: '全部',
      active: true,
    }, {
      id: 1,
      name: '未处理',
      active: false,
    }, {
      id: 2,
      name: '已忽略',
      active: false,
    }, {
      id: '3',
      name: '修复中',
      active: false,
    }, {
      id: '4',
      name: '已修复',
      active: false,
    }, ],
    hiddenTypeList: [{
      id: '',
      name: '全部',
      active: true,
    }, {
      id: 1,
      name: '低电压',
      active: false,
    }, {
      id: 2,
      name: '低电量',
      active: false,
    }, {
      id: '3',
      name: '燃气传感器故障',
      active: false,
    }, {
      id: '4',
      name: '烟雾传感器故障',
      active: false,
    }, {
      id: '5',
      name: '温度传感器故障',
      active: false,
    }, {
      id: '6',
      name: '压力传感器故障',
      active: false,
    }, {
      id: '7',
      name: '温湿度传感器故障',
      active: false,
    }, {
      id: '8',
      name: 'NB低电量',
      active: false,
    }, {
      id: '9',
      name: '硬件异常',
      active: false,
    }, {
      id: '10',
      name: '主电故障',
      active: false,
    }, {
      id: '11',
      name: '用传备电故障',
      active: false,
    }, {
      id: '12',
      name: '检测连接线路故障',
      active: false,
    }, {
      id: '13',
      name: '传感器异常',
      active: false,
    }, {
      id: '14',
      name: '漏电传感器接触故障',
      active: false,
    }, {
      id: '98',
      name: '故障',
      active: false,
    }, {
      id: '99',
      name: '其他',
      active: false,
    }, ],
    hiddenSourceList: [{
      id: '',
      name: '全部',
      active: true,
    }, {
      id: 0,
      name: '设备上报',
      active: false,
    }, {
      id: 1,
      name: '人工上报',
      active: false,
    }, ],

    // 工单
    workPage: 1,
    workList: [],
    workIsNextPage: true,
    workTriggered: false,
    workName: "",
    workType: "",
    workStatus: "",
    workStartTime: "",
    workEndTime: "",
    showWorkSearch: false, //筛选弹窗
    hasSearchWork: false, //是否有筛选
    workstatusList: [{
      id: '',
      name: '全部',
      active: true,
    }, {
      id: 1,
      name: '待派单',
      active: false,
    }, {
      id: 2,
      name: '待接单',
      active: false,
    }, {
      id: '3',
      name: '维修中',
      active: false,
    }, {
      id: '4',
      name: '待维保员审核',
      active: false,
    }, {
      id: '5',
      name: '待上报人审核',
      active: false,
    }, {
      id: '6',
      name: '已完成',
      active: false,
    }, {
      id: '7',
      name: '已忽略',
      active: false,
    }, ],
    workTypeList: [{
      id: '',
      name: '全部',
      active: true,
    }, {
      id: 0,
      name: '报警隐患工单',
      active: false,
    }, {
      id: 1,
      name: '上报隐患工单',
      active: false,
    }, ],
    mountingName: "",
  },
  async onLoad(options) {
    this.getDict('device_alarm_type');
    console.log('onLoad');
    await  this.getProductList() // 产品列表
    this.setAlarmHandleBeforeClose() //混入：告警处理相关函数
    this.setTabList()

    console.log(options, "options");
    // 公众号跳转
    if (options.imei) {
      // console.log('公众号跳转进来了');
      this.setData({
        alarmSearchValue: options.imei
      })
      //   console.log(options.orgId);

      // 获取单位列表
      const res = await reqOrgList(1, 99, {
        tenantId: app.globalData.tenantId,
        userId: app.globalData.userId,
        roleName: app.globalData.rolename,
      })
      if (res.code !== 20000) return showMsg(res.message)
      res.data.rows.forEach(item => {
        // 判断是否加入了此单位
        if (item.id == options.orgId) {
          app.globalData.orgId = item.id
          wx.setStorageSync('orgId', item.id);
          app.globalData.orgName = item.orgName
          wx.setStorageSync('orgName', item.orgName);
          app.globalData.flatType = item.flatType
          wx.setStorageSync('flatType', item.flatType);
          app.globalData.isTeamManager = item.role === 1 ? true : false //role为1：单位管理员 role为2：消防安全员
          wx.setStorageSync('isTeamManager', item.role === 1 ? true : false);
          return;
        }
      })

      if (app.globalData.orgId == options.orgId) {
        console.log('相等');
        this.getAlarmList()
      }
    }
  },
  onShow() {
    console.log("onShow", this.data.orgInfo);
    // this.getDicts()
    const {
      orgInfo
    } = this.data
    if (orgInfo && orgInfo.orgId) {
      app.globalData.orgId = orgInfo.orgId
      wx.setStorageSync('orgId', orgInfo.orgId);
      app.globalData.orgName = orgInfo.orgName
      wx.setStorageSync('orgName', orgInfo.orgName);
      app.globalData.orgInfo = orgInfo
      wx.setStorageSync('orgInfo', orgInfo);
    }
    if (!app.globalData.isProprietor && app.globalData.orgId2 != 0) {
      // 装维人员
      this.setData({
        tabList: [{
          id: 0,
          name: '告警',
          count: '',
          src: '/statics/images/alarm.png',
        }, {
          id: 1,
          name: '隐患',
          count: '',
          src: '/statics/images/message/device_msg.png',
        },
         {
          id: 2,
          name: '工单',
          count: '',
          src: '/statics/images/message/home_msg.png',
        },
       ],
      })
      this.getWorkOrder() //工单数量
    }
    if (app.globalData.isProprietor) {
      // 业主
      this.setData({
        tabList: [{
          id: 0,
          name: '告警',
          count: '',
          src: '/statics/images/alarm.png',
        }, {
          id: 1,
          name: '隐患',
          count: '',
          src: '/statics/images/message/device_msg.png',
        },
       ],
      })
    }
    this.getHiddenDanger() //隐患数量
    this.getUntreatedAlarm() // 获取未处理告警数量
    this.getTabBar().init();
    console.log(this.data.currentTab);
    // if(app.globalData.isAlarm){
    //     app.globalData.isAlarm = false 
    //     wx.setStorageSync('isAlarm', false);//是否从告警处理记录出来
    //     return;
    // }
    if (this.data.currentTab == 0) {
      this.resetSearch()
    } else if (this.data.currentTab == 1) {
      this.resetHidden()
    } else if (this.data.currentTab == 2 && !app.globalData.isProprietor) {
      this.resetWork()
    }
    this.resetSearch2() //清空筛选信息
  },
//  async getDicts(){
//     const res = await getDicts('device_alarm_type')
//     if (res.code !== 20000) return showMsg(res.message)
//     console.log(res,'111');
//   },
  onHide() {
    console.log('onHide');
  },
  // 根据字典数据获取告警名称
  // getAlarmName(alarmType) {
  //   console.log(alarmType);
  //   const dict = this.data.dictData.find(item => item.dickValue == alarmType);
  //   console.log(dict);
  //   return dict ? dict.dickLabel : '未知告警类型';
  // },
  // 
  setTabList() {
    const {
      tenantId
    } = app.globalData
    this.setData({
      tenantId
    })
    if (!(tenantId && tenantId != '0' && tenantId.length > 5)) {
      let {
        tabList
      } = this.data
      tabList.splice(1, 1)
      this.setData({
        tabList,
      })
    }
  },

  // 机构确定
  confirmOrg() {
    this.getWorkOrder() //工单数量
    this.getHiddenDanger() //隐患数量
    this.getUntreatedAlarm() // 获取未处理告警数量

    if (this.data.currentTab == 0) {
      this.resetSearch()
    } else if (this.data.currentTab == 1) {
      this.resetHidden()
    } else if (this.data.currentTab == 2 && !app.globalData.isProprietor) {
      this.resetWork()
    }
  },

  // 单位选择确定
  confirmUnit() {
    this.getWorkOrder() //工单数量
    this.getHiddenDanger() //隐患数量
    this.getUntreatedAlarm() // 获取未处理告警数量

    if (this.data.currentTab == 0) {
      this.resetSearch()
    } else if (this.data.currentTab == 1) {
      this.resetHidden()
    } else if (this.data.currentTab == 2 && !app.globalData.isProprietor) {
      this.resetWork()
    }
  },

  /**
   * @name: 滑动切换
   */
  bindChangeTab(e) {
    let {
      current
    } = e.detail
    this.setData({
      currentTab: current
    })
    if (current == 0) {
      this.getInitAlarmList() // 操作列表后回到最初状态
    }
    if (current == 1) {
      this.setData({
        hiddenPage: 1,
        hiddenIsNextPage: true,
      })
      // this.hiddenRefresh()
      this.gethidden()
    }
    if (app.globalData.isProprietor) return; //业主不查看工单
    if (current == 2) {
      // this.workRefresh()
      this.setData({
        workPage: 1,
        workIsNextPage: true,
      })
      this.getwork()
    }
  },
  // 清空筛选信息
  resetSearch2() {
    let {
      statusList,
      productList,
      dictData
    } = this.data
    statusList.forEach(item => {
      if (item.id === '') {
        item.active = true
      } else {
        item.active = false
      }
    })
    dictData.forEach(item => {
      if (item.dickValue === '') {
        item.active = true
      } else {
        item.active = false
      }
    })
    productList.forEach(item => {
      if (item.id === '') {
        item.active = true
      } else {
        item.active = false
      }
    })
    let {
      alarmStatus,
      alarmType,
      alarmStartTime,
      deviceType,
      classMark
    } = this.data;
    let hasSearch = false;
    hasSearch = (alarmStatus || alarmType || alarmStartTime || deviceType || classMark) ? true : false
    this.setData({
      hasSearch,
      statusList,
      dictData,
      productList,
      alarmStatus: '',
      alarmType: '',
      alarmStartTime: '',
      alarmEndTime: '',
      deviceType: '',
      classMark: "", // 产品型号
      classMarkList: [], // 产品型号
      showSearch: false,
    })
  },
  // 产品列表
  async getProductList() {
    const res = await reqProductList()
    if (res.code !== 20000) return showMsg(res.message)
    let {
      rows
    } = res.data
    console.log(rows);
    rows.unshift({
      id: '',
      name: '全部',
      active: true
    })
    this.setData({
      productList: rows
    })
  },
  /**
   * @name:   点击切换
   * @msg:    currentTab  
   * @param {*} e
   * @return {*}
   */
  swichTab(e) {
    let {
      id
    } = e.currentTarget.dataset
    this.setData({
      currentTab: id
    })
  },

  // 隐患列表
  async gethidden() {
    let params = {
      userId: app.globalData.userId,
      roleName: app.globalData.rolename,
      tenantId: app.globalData.tenantId,
      orgId: this.data.orgInfo.orgId,
      source: this.data.hiddenSource,
      imei: this.data.hiddenSearchValue,
      type: this.data.hiddenType,
      status: this.data.hiddenStatus,
      startTime: this.data.hiddenStartTime,
      endTime: this.data.hiddenEndTime,
    }
    const res = await reqhiddenDangerpage(this.data.hiddenPage, params)
    console.log(res);
    if (res.code !== 20000) return showMsg(res.message)
    let {
      rows
    } = res.data
    if (this.data.hiddenPage === 1) {
      this.setData({
        hiddenList: rows,
        hiddenIsNextPage: true
      })
    } else if (this.data.hiddenPage > 1 && (rows && rows.length)) {
      this.setData({
        hiddenList: this.data.hiddenList.concat(rows),
        hiddenIsNextPage: true
      })
    } else if (this.data.hiddenPage > 1 && (!rows || !rows.length)) {
      showMsg('已经到底啦~')
      this.setData({
        hiddenIsNextPage: false
      })
    }
  },
  // 滚动到底部触发
  hiddenLower() {
    if (!this.data.hiddenIsNextPage) return
    this.setData({
      hiddenPage: this.data.hiddenPage + 1,
    })
    this.gethidden()
  },
  // 下拉刷新
  async hiddenRefresh() {
    this.setData({
      // hiddenList: [],
      hiddenPage: 1,
      hiddenIsNextPage: true,
      hiddenTriggered: true,
    })
    await this.gethidden()
    this.setData({
      hiddenTriggered: false,
    })
  },
  // 输入框搜索
  hiddenSearchChange(e) {
    // e.detail='11'
    // e.detail = e.detail.replace(/[^0-9]/g, '');
    e.detail = e.detail.replace(/[\u4e00-\u9fa5]/g, '');
    console.log(e.detail);
    // 防止输入字母也触发接口调用
    if (this.data.hiddenSearchValue2 == e.detail) {
      this.setData({
        hiddenSearchValue: e.detail,
        hiddenSearchValue2: e.detail,
      })
      return;
    }
    this.setData({
      hiddenSearchValue: e.detail,
      hiddenSearchValue2: e.detail,
      hiddenPage: 1,
      hiddenIsNextPage: true
    })
    clearTimeout(this.data.timer)
    this.data.timer = setTimeout(() => {
      this.gethidden()
    }, 1000)
  },
  // 点击扫码获取imei
  hiddenimeiScan() {
    const that = this
    let qrcode = ''
    wx.scanCode({
      success(res) {
        qrcode = res.result;
        if (!qrcode) return showMsg('扫描失败，请重新扫描')
        if (qrcode.length >= 15) {
          let reg = /^\d+$/.test(qrcode)
          if (reg) {
            qrcode = qrcode.substring(0, 15);
            that.setData({
              hiddenSearchValue: qrcode,
            })
            that.gethidden()
          } else {
            qrcode = qrcode.substr(qrcode.indexOf(86), 15)
            that.setData({
              hiddenSearchValue: qrcode,
            })
            that.gethidden()
          }
        } else {
          showMsg('扫描失败，请重新扫描')
          return
        }
      }
    })
  },
  // 点击筛选
  hiddenclickSearch() {
    this.setData({
      showHiddenSearch: true
    })
  },
  // 点击关闭筛选
  closeHiddenSearch() {
    this.setData({
      showHiddenSearch: false
    })
  },
  // 确定筛选点击
  confirmhiddenSearch() {
    let {
      hiddenStatus,
      hiddenType,
      hiddenStartTime,
      hiddenSource
    } = this.data;
    let hasSearchHidden = false;
    hasSearchHidden = (hiddenStatus || hiddenType || hiddenStartTime || hiddenSource || hiddenSource === 0) ? true : false
    this.setData({
      showHiddenSearch: false,
      hasSearchHidden,
      hiddenPage: 1
    })
    this.gethidden()
  },
  // 重置筛选
  resetHidden() {
    let {
      hiddenstatusList,
      hiddenTypeList,
      hiddenSourceList
    } = this.data
    hiddenstatusList.forEach(item => {
      if (item.id === '') {
        item.active = true
      } else {
        item.active = false
      }
    })
    hiddenTypeList.forEach(item => {
      if (item.id === '') {
        item.active = true
      } else {
        item.active = false
      }
    })
    hiddenSourceList.forEach(item => {
      if (item.id === '') {
        item.active = true
      } else {
        item.active = false
      }
    })
    this.setData({
      hiddenstatusList,
      hiddenTypeList,
      hiddenSourceList,
      hiddenType: "",
      hiddenStatus: "",
      hiddenSource: "",
      hiddenStartTime: "",
      hiddenEndTime: "",

      // hiddenList: [],
      hiddenPage: 1,
      hiddenIsNextPage: true,
    })
    this.confirmhiddenSearch()
  },
  // 点击处理状态
  statushiddenClick(e) {
    let {
      id
    } = e.currentTarget.dataset
    let {
      hiddenstatusList
    } = this.data
    hiddenstatusList.forEach(item => {
      if (item.id === id) {
        item.active = true
      } else {
        item.active = false
      }
    })
    this.setData({
      hiddenstatusList,
      hiddenStatus: id
    })
  },
  // 点击隐患源
  hiddenSourceClick(e) {
    let {
      id
    } = e.currentTarget.dataset
    let {
      hiddenSourceList
    } = this.data
    hiddenSourceList.forEach(item => {
      if (item.id === id) {
        item.active = true
      } else {
        item.active = false
      }
    })
    this.setData({
      hiddenSourceList,
      hiddenSource: id
    })
  },
  // 点击隐患类型
  hiddenTypeClick(e) {
    let {
      id
    } = e.currentTarget.dataset
    let {
      hiddenTypeList
    } = this.data
    hiddenTypeList.forEach(item => {
      if (item.id === id) {
        item.active = true
      } else {
        item.active = false
      }
    })
    this.setData({
      hiddenTypeList,
      hiddenType: id
    })
  },
  // 隐藏时间组件
  hiddenTimeClose() {
    this.setData({
      showAlarmTime: false,
    });
  },
  // 确定时间
  hiddenTimeChange(e) {
    this.setData({
      hiddenStartTime: e.detail.startTime,
      hiddenEndTime: e.detail.endTime,
    });
  },
  // 去隐患处理或详情
  gohiddenDetail(e) {
    let {
      item
    } = e.currentTarget.dataset
    // this.data.productList.forEach(e=>{
    //     if(e.deviceType==item.deviceType){
    //         item.pic=e.pic;//添加产品图片
    //     }
    // })
    let info = JSON.stringify(item)
    console.log(item);
    if (app.globalData.isProprietor) {
      wx.navigateTo({
        url: `/packageA/pages/message-index-page/hidden-details/hidden-details?info=${info}`,
      })
      return;
    }
    if (item.status == 1) {
      wx.navigateTo({
        url: `/packageA/pages/message-index-page/hidden-handle/hidden-handle?info=${info}`,
      })
    } else {
      wx.navigateTo({
        url: `/packageA/pages/message-index-page/hidden-details/hidden-details?info=${info}`,
      })
    }
  },
  // 进入隐患相关节点详情页
  // onDangerDetail(e) {
  //     let status = e.currentTarget.dataset.status
  //     wx.navigateTo({
  //         url: `/pages/index-inside-page/dangerList/dangerList?status=${status}`,
  //     })
  // },
  // 隐患节点统计
  async getStatistics() {
    for (let i = 2; i < 6; i++) {
      console.log(i);
      let res = await reqStatistics({
        tenantId: app.globalData.tenantId,
        orgId: this.data.orgInfo.orgId,
        status: i
      })
      if (res.code !== 20000) return showMsg(res.message)
      if (i == 2) {
        // 隐患审核
        this.setData({
          dangerExmine: res.data.row
        })
      } else if (i == 3) {
        // 处理工单
        this.setData({
          handleWorkOrder: res.data.row
        })
      } else if (i == 4) {
        // 处理审核
        this.setData({
          workOrderExmine: res.data.row
        })
      } else if (i == 5) {
        // 处理审核
        this.setData({
          handleFinished: res.data.row
        })
      }
    }

  },
  // 获取未处理告警数量
  async getUntreatedAlarm() {
    let params = {
      userId: app.globalData.userId,
      orgId: this.data.orgInfo.orgId,
      roleName: app.globalData.rolename,
      tenantId: app.globalData.tenantId,
    }
    const res = await reqUntreatedAlarm(params)
    if (res.code !== 20000) return showMsg(res.message)
    let {
      total
    } = res.data
    console.log(total, '未处理告警总数');
    this.setData({
      'tabList[0].count': total == 0 ? '' : total,
    })
  },
  // 单位未处理隐患数量
  async getHiddenDanger() {
    let params = {
      orgId: this.data.orgInfo.orgId,
      userId: app.globalData.userId,
      roleName: app.globalData.rolename,
      tenantId: app.globalData.tenantId,
    }
    const res = await reqHiddenDanger(params)
    if (res.code !== 20000) return showMsg(res.message)
    let {
      total
    } = res.data
    console.log(total, '');
    this.setData({
      'tabList[1].count': total == 0 ? '' : total,
    })
  },
  // 单位未处理工单数量
  async getWorkOrder() {
    let params = {
      orgId: this.data.orgInfo.orgId,
      userId: app.globalData.userId,
      roleName: app.globalData.rolename,
      tenantId: app.globalData.tenantId,
    }
    const res = await reqWorkOrder(params)
    if (res.code !== 20000) return showMsg(res.message)
    let {
      total
    } = res.data
    console.log(total, '');
    this.setData({
      'tabList[2].count': total == 0 ? '' : total,
    })
  },

  // 获取告警列表
  async getAlarmList() {
    let params = {
      tenantId: app.globalData.tenantId,
      userId: app.globalData.userId,
      orgId: this.data.orgInfo.orgId,
      roleName: app.globalData.rolename,
      status: this.data.alarmStatus,
      alarmType: this.data.alarmType,
      imei: this.data.alarmSearchValue,
      deviceType: this.data.deviceType,
      classMark: this.data.classMark,
      startTime: this.data.alarmStartTime,
      endTime: this.data.alarmEndTime,
      name: this.data.mountingName,
    }
    const res = await reqAlarmList(this.data.alarmPage, 10, params)
    if (res.code !== 20000) return showMsg(res.message)
    let {
      rows
    } = res.data
    let {
      productList,
      dictData
    } = this.data
    if (rows && rows.length) {
      rows.forEach(item => {
        productList.forEach(citem => {
          if (item.deviceType == citem.deviceType) {
            item.type = citem.name; //产品类型
          }
        })
        dictData.forEach(dict => {
          if (item.alarmType == dict.dickValue) {
            item.dickLabel = dict.dickLabel; //告警类型
          }
        })
      });
    }
    if (this.data.alarmPage === 1) {
      this.setData({
        alarmList: rows,
        alarmIsNextPage: true
      })
    } else if (this.data.alarmPage > 1 && (rows && rows.length)) {
      this.setData({
        alarmList: this.data.alarmList.concat(rows),
        alarmIsNextPage: true
      })
    } else if (this.data.alarmPage > 1 && (!rows || !rows.length)) {
      showMsg('已经到底啦~')
      this.setData({
        alarmIsNextPage: false
      })
    }
  },
  // 滚动到底部触发
  alarmLower() {
    if (!this.data.alarmIsNextPage) return
    this.setData({
      alarmPage: this.data.alarmPage + 1,
    })
    this.getAlarmList()
  },
  // 下拉刷新
  async alarmRefresh() {
    this.setData({
      // alarmList: [],
      alarmPage: 1,
      alarmIsNextPage: true,
      alarmTriggered: true,
    })
    await this.getAlarmList()
    this.setData({
      alarmTriggered: false,
    })
  },

  // 操作列表后回到最初状态
  getInitAlarmList() {
    this.setData({
      alarmPage: 1,
      alarmIsNextPage: true,
      // alarmList: []
    })
    this.getAlarmList()
  },

  // 输入框搜索
  alarmSearchChange(e) {
    // e.detail='11'
    // e.detail = e.detail.replace(/[^0-9]/g, '');
    e.detail = e.detail.replace(/[\u4e00-\u9fa5]/g, '');
    console.log(e.detail);
    // 防止输入字母也触发接口调用
    if (this.data.alarmSearchValue2 == e.detail) {
      this.setData({
        alarmSearchValue: e.detail,
        alarmSearchValue2: e.detail,
      })
      return;
    }
    this.setData({
      alarmSearchValue: e.detail,
      alarmSearchValue2: e.detail,
      alarmPage: 1,
      alarmIsNextPage: true
    })
    clearTimeout(this.data.timer)
    this.data.timer = setTimeout(() => {
      this.getAlarmList()
    }, 1000)
  },
  // js判断字符串是否为JSON格式
  isjson(str) {
    if (typeof str == 'string') {
      try {
        var obj = JSON.parse(str);
        if (typeof obj == 'object' && obj) {
          return true;
        } else {
          return false;
        }

      } catch (e) {
        console.log('error：' + str + '!!!' + e);
        return false;
      }
    }
    console.log('It is not a string!')
  },
  // 点击扫码获取imei
  imeiScan() {
    const that = this
    let qrcode = ''
    wx.scanCode({
      success(res) {
        qrcode = res.result;
        if (!qrcode) return showMsg('扫描失败，请重新扫描')
        if (qrcode.length >= 3) {
          if (that.isjson(qrcode)) {
            const result = JSON.parse(qrcode);
            // JSON字符格式
            that.setData({
              alarmSearchValue: result.ID, //威视达康摄像机取值，后续看需求更改 lc
            })
            clearTimeout(that.data.timer)
            that.data.timer = setTimeout(() => {
              that.getInitAlarmList()
            }, 500)
          } else {
            // 非JSON格式
            that.setData({
              alarmSearchValue: qrcode,
            })
            clearTimeout(that.data.timer)
            that.data.timer = setTimeout(() => {
              that.getInitAlarmList()
            }, 500)
          }
        } else {
          showMsg('扫描失败，请重新扫描')
          return
        }
      }
    })
  },
  // 点击筛选
  clickSearch() {
    this.setData({
      showSearch: true
    })
  },
  // 点击关闭筛选
  closeSearch() {
    this.setData({
      showSearch: false
    })
  },
  // 点击处理状态
  statusClick(e) {
    let {
      id
    } = e.currentTarget.dataset
    let {
      statusList
    } = this.data
    statusList.forEach(item => {
      if (item.id === id) {
        item.active = true
      } else {
        item.active = false
      }
    })
    this.setData({
      statusList,
      alarmStatus: id
    })
  },
  // 点击告警类型
  alarmTypeClick(e) {
    let {
      id
    } = e.currentTarget.dataset
    let {
      dictData
    } = this.data
    dictData.forEach(item => {
      if (item.dickValue === id) {
        item.active = true
      } else {
        item.active = false
      }
    })
    this.setData({
      dictData,
      alarmType: id
    })
  },
  // 点击设备类型
  deviceTypeClick(e) {
    // console.log(e);
    // console.log(e.currentTarget.dataset.devicetype);
    let {
      productList
    } = this.data
    let productId = '';
    productList.forEach(item => {
      if (item.deviceType == e.currentTarget.dataset.devicetype) {
        item.active = true
        productId = item.id
      } else {
        item.active = false
      }
    })
    this.setData({
      productList,
      deviceType: e.currentTarget.dataset.devicetype,
      classMark: "", // 产品型号
      classMarkList: [] // 产品型号
    })
    if (productId == '') return;
    this.ProductModel(productId)
  },
  // 产品型号
  async ProductModel(productId) {
    const res = await reqProductModel({
      productId: productId
    })
    if (res.code !== 20000) return showMsg(res.message)
    this.setData({
      classMarkList: res.data.rows
    })
  },
  // 点击产品型号
  classMarkClick(e) {
    // console.log(e);
    // console.log(e.currentTarget.dataset.model);
    let {
      classMarkList
    } = this.data
    classMarkList.forEach(item => {
      if (item.model == e.currentTarget.dataset.model) {
        item.active = true
      } else {
        item.active = false
      }
    })
    this.setData({
      classMarkList,
      classMark: e.currentTarget.dataset.model
    })
  },
  // 点击显示时间组件
  clickShowAlarmTime() {
    this.setData({
      showAlarmTime: true,
    });
  },
  // 隐藏时间组件
  alarmTimeClose() {
    this.setData({
      showAlarmTime: false,
    });
  },
  // 确定时间
  alarmTimeChange(e) {
    this.setData({
      alarmStartTime: e.detail.startTime,
      alarmEndTime: e.detail.endTime,
    });
  },

  // 重置筛选
  resetSearch() {
    let {
      statusList,
      dictData,
      productList
    } = this.data
    statusList.forEach(item => {
      if (item.id === '') {
        item.active = true
      } else {
        item.active = false
      }
    })
    dictData.forEach(item => {
      if (item.dickValue === '') {
        item.active = true
      } else {
        item.active = false
      }
    })
    productList.forEach(item => {
      if (item.id === '') {
        item.active = true
      } else {
        item.active = false
      }
    })
    this.setData({
      statusList,
      dictData,
      productList,
      alarmStatus: '',
      alarmType: '',
      alarmStartTime: '',
      alarmEndTime: '',
      deviceType: '',
      classMark: "", // 产品型号
      classMarkList: [], // 产品型号
      mountingName: ""
    })
    this.confirmSearch()
  },
  // 确定筛选点击
  confirmSearch() {
    let {
      alarmStatus,
      alarmType,
      alarmStartTime,
      deviceType,
      classMark
    } = this.data;
    let hasSearch = false;
    hasSearch = (alarmStatus || alarmType || alarmStartTime || deviceType || classMark) ? true : false
    this.setData({
      showSearch: false,
      hasSearch
    })
    this.getInitAlarmList()
  },



  // 点击复制imei
  clickCopyImei(e) {
    let {
      imei
    } = e.currentTarget.dataset
    console.log(e);
    console.log(imei);
    wx.setClipboardData({
      data: imei,
      success(res) {
        wx.getClipboardData({
          success(res) {
            showMsg(`${imei} 已复制`)
          }
        })
      }
    })
  },

  // 去告警详情
  goAlarmDetail(e) {
    let {
      item
    } = e.currentTarget.dataset
    this.data.productList.forEach(e => {
      if (e.deviceType == item.deviceType) {
        item.pic = e.pic; //添加产品图片
      }
    })
    let info = JSON.stringify(item)
    wx.navigateTo({
      url: `/packageA/pages/message-index-page/alarm-detail/alarm-detail?info=${info}`,
    })
  },
  catchTouchMove() {
    return false;
  },

  // 工单开始
  async getwork() {
    let params = {
      userId: app.globalData.userId,
      roleName: app.globalData.rolename,
      tenantId: app.globalData.tenantId,
      orgId: this.data.orgInfo.orgId,
      name: this.data.workName,
      type: this.data.workType,
      status: this.data.workStatus,
      startTime: this.data.workStartTime,
      endTime: this.data.workEndTime,
    }
    const res = await reqworkOrderpage(this.data.workPage, params)
    console.log(res);
    if (res.code !== 20000) return showMsg(res.message)
    let {
      rows
    } = res.data
    if (this.data.workPage === 1) {
      this.setData({
        workList: rows,
        workIsNextPage: true
      })
    } else if (this.data.workPage > 1 && (rows && rows.length)) {
      this.setData({
        workList: this.data.workList.concat(rows),
        workIsNextPage: true
      })
    } else if (this.data.workPage > 1 && (!rows || !rows.length)) {
      showMsg('已经到底啦~')
      this.setData({
        workIsNextPage: false
      })
    }
  },
  // 滚动到底部触发
  workLower() {
    if (!this.data.workIsNextPage) return
    this.setData({
      workPage: this.data.workPage + 1,
    })
    this.getwork()
  },
  // 下拉刷新
  async workRefresh() {
    this.setData({
      // workList: [],
      workPage: 1,
      workIsNextPage: true,
      workTriggered: true,
    })
    await this.getwork()
    this.setData({
      workTriggered: false,
    })
  },
  // 输入框搜索
  workSearchChange(e) {
    // e.detail='11'
    // e.detail = e.detail.replace(/[^0-9]/g, '');
    console.log(e.detail);
    this.setData({
      workName: e.detail,
      workPage: 1,
      workIsNextPage: true
    })
    clearTimeout(this.data.timer)
    this.data.timer = setTimeout(() => {
      this.getwork()
    }, 1000)
  },
  // 点击筛选
  workclickSearch() {
    this.setData({
      showWorkSearch: true
    })
  },
  // 点击关闭筛选
  closeWorkSearch() {
    this.setData({
      showWorkSearch: false
    })
  },
  // 点击工单状态
  statusworkClick(e) {
    let {
      id
    } = e.currentTarget.dataset
    let {
      workstatusList
    } = this.data
    workstatusList.forEach(item => {
      if (item.id === id) {
        item.active = true
      } else {
        item.active = false
      }
    })
    this.setData({
      workstatusList,
      workStatus: id
    })
  },
  // 点击工单类型
  workTypeClick(e) {
    let {
      id
    } = e.currentTarget.dataset
    let {
      workTypeList
    } = this.data
    workTypeList.forEach(item => {
      if (item.id === id) {
        item.active = true
      } else {
        item.active = false
      }
    })
    this.setData({
      workTypeList,
      workType: id
    })
  },
  // 确定时间
  workTimeChange(e) {
    this.setData({
      workStartTime: e.detail.startTime,
      workEndTime: e.detail.endTime,
    });
  },
  // 确定筛选点击
  confirmworkSearch() {
    let {
      workStatus,
      workType,
      workStartTime,
    } = this.data;
    let hasSearchWork = false;
    hasSearchWork = (workStatus || workType || workStartTime) ? true : false
    this.setData({
      showWorkSearch: false,
      hasSearchWork,
      workPage: 1
    })
    this.getwork()
  },
  // 重置筛选
  resetWork() {
    let {
      workstatusList,
      workTypeList,
    } = this.data
    workstatusList.forEach(item => {
      if (item.id === '') {
        item.active = true
      } else {
        item.active = false
      }
    })
    workTypeList.forEach(item => {
      if (item.id === '') {
        item.active = true
      } else {
        item.active = false
      }
    })
    this.setData({
      workstatusList,
      workTypeList,
      workType: "",
      workStatus: "",
      workStartTime: "",
      workEndTime: "",

      // workList: [],
      workPage: 1,
      workIsNextPage: true,
    })
    this.confirmworkSearch()
  },
  // 忽略工单
  clickDelete(e) {
    console.log(e.currentTarget.dataset.item.id);
    Dialog.confirm({
        title: '温馨提示',
        message: '是否要忽略此工单?',
      })
      .then(async () => {
        const res = await reqworkOrderupdate({
          id: e.currentTarget.dataset.item.id,
          userId: app.globalData.userId,
          username: app.globalData.username,
          status: 10,
          result: '忽略',
          remark: "",
          maintenanceUserId: '',
          picList: [],
          videoFile: ""
        })
        if (res.code != 20000) return showMsg(res.message);
        showMsg("忽略成功！")
        setTimeout(() => {
          this.workRefresh()
        }, 500)
      })
      .catch(() => {});
  },
  // 去工单处理或详情
  goworkDetail(e) {
    let {
      item
    } = e.currentTarget.dataset
    let info = JSON.stringify(item)
    console.log(item);
    wx.navigateTo({
      url: `/packageA/pages/message-index-page/work-details/work-details?info=${info}`,
    })
  },
  // van-popup弹窗添加滚动条后导致背景内容跟随滑动
  touchmove() {},
  // 获取输入值
  searchValueChange(e) {
    this.setData({
      mountingName: e.detail.value
    })
  },
})